package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.elinkway.infinitemovies.adapter.SplashViewPagerAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.async.RequestPublicIpTask;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.bean.HzPayload;
import com.elinkway.infinitemovies.bean.InitInfo;
import com.elinkway.infinitemovies.bean.NewAdDataBean;
import com.elinkway.infinitemovies.bean.SDKPayload;
import com.elinkway.infinitemovies.bean.ServerPayload;
import com.elinkway.infinitemovies.bean.TtPayload;
import com.elinkway.infinitemovies.bean.XfPayload;
import com.elinkway.infinitemovies.bean.YzPayload;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.dao.PreferencesManager;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.InitInfoParser;
import com.elinkway.infinitemovies.http.requesttask.RequestAdTask;
import com.elinkway.infinitemovies.listener.MyOnAdListener;
import com.elinkway.infinitemovies.selfdata.AdRequestStatis;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.SelfDataConstant;
import com.elinkway.infinitemovies.selfdata.bean.LaunchDurationDataRecord;
import com.elinkway.infinitemovies.utils.AdStatisticsSp;
import com.elinkway.infinitemovies.utils.LogCat;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.MyLocationManager;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.BaiduNativeAdView;
import com.elinkway.infinitemovies.view.GdtNativeAdView;
import com.elinkway.infinitemovies.view.GdtSplashAdView;
import com.elinkway.infinitemovies.view.HzPayAdView;
import com.elinkway.infinitemovies.view.TtPayAdView;
import com.elinkway.infinitemovies.view.XfPayAdView;
import com.elinkway.infinitemovies.view.YzPayAdView;
import com.elinkway.infinitemovies.widget.CirclePageIndicator;
import com.le123.ysdq.BuildConfig;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by wangyemin on 2015/11/3.
 * <p/>
 * 启动页
 */
public class SplashActivity extends Activity implements OnClickListener, Handler.Callback {

    private String TAG = "SplashActivity";
    private static final int MAX_WAIT_TIME = 5000;
    public static final int MSG_START_MAIN = 0;
    private static int TIMEINTERVAL = 2000; // 2s
    private static String START_FROM_NOTIFICATION = "start_from_notification";
    private ImageView mLaunchImage; // 网络请求图
    private RelativeLayout mAdLayout;
    private RelativeLayout mBaiduAdLayout;
    private View adView;
    private ImageView mAdImage;
    private LinearLayout directToMianLl;
    private TextView mAdTextTime;
    private TextView mAdText;

    private boolean isShowAd;// 广告显示
    private boolean isPlatControll = true;// 平台控制(逻辑已在服务端处理，无需客户端添加逻辑)
    private boolean isCityControll = true;// 地域控制(逻辑已在服务端处理，无需客户端添加逻辑)
    private String adImageUrl; // 启动广告图
    private String adUrl; // 广告url
    private int adTime = 5; // 广告显示时间
    private int leftTime;

    private Handler mHandler;
    private Runnable mTask;
    private boolean isRun;
    private int backCount = 0;

    private Context mContext;
    private boolean isAdClick;
    private boolean isDirectToMainclick;

    public static String ISADCLICK = "isadclick";
    public static String ADURL = "adurl";
    public static String LAUNCHLOG = "lauchlog";

    private String cityInfo;

    private ViewPager mSplashViewPager;

    private ArrayList<ImageView> mSplashViews;

    private int mSplashViewCount = 3;

    private SplashViewPagerAdapter mSplashViewPagerAdapter;

    private CirclePageIndicator mCirclePageIndicator;

    private Boolean isFirstTimeEnter;

    private ImageView mExperienceView;

    private float preX;

    private float preY;

    private int mCurrentSelectPage;
	
    private boolean isJump = true;

    private boolean loaded = false;

    private boolean isClick = false;

    private int mResumeTimes = 0;

    private LaunchDurationDataRecord launchDuration; // 启动时长日志
    private ServerPayload mServerAdInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState ) {
        MoviesApplication.isSaveLogContinue = true;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        MoviesApplication.getInstance().setTopActivity(SplashActivity.this);
        setContentView(R.layout.activity_splash);
        launchDuration = MyDataRecordCreater.build(LaunchDurationDataRecord.class);
        launchDuration.setAcode(LaunchDurationDataRecord.CODE_LAUNCH_DURATION);
        launchDuration.setSplashOncreate(System.currentTimeMillis() + ""); // 埋点记录
        initView();
        bindListener();
        initData();
        MoviesApplication.getInstance().setLastPageClassName(TAG);
    }

    private void initView() {
        mContext = this;
        mCirclePageIndicator = (CirclePageIndicator) findViewById(R.id.pi_splash_view_pager);
        mSplashViewPager = (ViewPager) findViewById(R.id.vp_splash_view);
        mExperienceView = (ImageView) findViewById(R.id.tv_direct_main);
        mLaunchImage = (ImageView) findViewById(R.id.launch_image);
        mAdLayout = (RelativeLayout) findViewById(R.id.ad_layout);
        mAdImage = (ImageView) findViewById(R.id.ad_image);
        directToMianLl = (LinearLayout) findViewById(R.id.direct_to_main_ll);
        mAdTextTime = (TextView) findViewById(R.id.ad_text_time);
        mAdText = (TextView) findViewById(R.id.ad_text);
        mBaiduAdLayout = (RelativeLayout) findViewById(R.id.baidu_ad_layout);
        adView = findViewById(R.id.nativeADContainer);
        mHandler = new Handler(this);
        mHandler.sendEmptyMessageDelayed(MSG_START_MAIN, MAX_WAIT_TIME);
    }

    private void bindListener() {
        directToMianLl.setOnClickListener(this);
        mAdText.setOnClickListener(this);
        mAdImage.setOnClickListener(this);
        mExperienceView.setOnClickListener(this);
    }

    private void initData() {
        initCirclePageIndicator();
//        initSplashViewPager();
        cityInfo = SharePreferenceManager.getVaule(mContext,
                MyLocationManager.LOCATIONKEY, null);
        LogUtils.e(TAG, "1-->launch cityInfo is " + cityInfo);
        LogUtils.e("MyLocationManager", "launch cityInfo is " + cityInfo);
        load();
    }

    private void initCirclePageIndicator() {
        mCirclePageIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                LogCat.e(TAG, "onPageScrolled " + position + " " + positionOffset + " " + positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                LogCat.e(TAG, "onPageSelected " + position);
                mCurrentSelectPage = position;
                if (mCurrentSelectPage == mSplashViews.size() - 1) {
                    mExperienceView.setVisibility(View.VISIBLE);
                    mCirclePageIndicator.setVisibility(View.GONE);
                } else {
                    mExperienceView.setVisibility(View.GONE);
                    mCirclePageIndicator.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                LogCat.e(TAG, "onPageScrollStateChanged " + state);
            }
        });
        mCirclePageIndicator.setStrokeColor(0);
        mCirclePageIndicator.setPageColor(0xFFEEEEEE);
        mCirclePageIndicator.setFillColor(0xFF0177FF);
        int radius = getResources().getDimensionPixelSize(R.dimen.len_12dp) / 2;
        mCirclePageIndicator.setRadius(radius);
        mCirclePageIndicator.setStrokeWidth(0);
    }

    private void initSplashViewPager() {
        mSplashViews = new ArrayList<>();
        mSplashViewCount = 3;
        for (int i = 0; i < mSplashViewCount; i++) {
            ImageView imageView = new ImageView(SplashActivity.this);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if (i == 0) {
                imageView.setImageResource(R.drawable.splash_launch_first);
            } else if (i == 1) {
                imageView.setImageResource(R.drawable.splash_launch_second);
            } else if (i == 2) {
                imageView.setImageResource(R.drawable.splash_launch_third);
            }
            mSplashViews.add(imageView);
        }
        mSplashViewPagerAdapter = new SplashViewPagerAdapter(mSplashViews);
        mSplashViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (mSplashViews != null &&
                                mCurrentSelectPage == mSplashViews.size() - 1) {
                            preX = event.getX();
                            preY = event.getY();
                        }
                        LogCat.e(TAG, "ACTION_DOWN " + event.getX() + " " + event.getY());
                        break;
                    case MotionEvent.ACTION_UP:
                        float moveX = 0;
                        float moveY = 0;
                        if (mSplashViews != null &&
                                mCurrentSelectPage == mSplashViews.size() - 1) {
                            moveX = preX - event.getX();
                            moveY = Math.abs(preY - event.getY());
                            if (moveX > 50 && moveY < 500) {
//                                redirectToMain();
                            }
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                }
                return false;
            }
        });
    }

    private void showSplashViewPager() {
        mSplashViewPager.setVisibility(View.VISIBLE);
        mSplashViewPager.setAdapter(mSplashViewPagerAdapter);
        mCirclePageIndicator.setVisibility(View.VISIBLE);
        mCirclePageIndicator.setViewPager(mSplashViewPager);
        mSplashViewPager.setCurrentItem(0);

    }

    private void load(){
        isFirstTimeEnter = PreferencesManager.getInstance().isFirstTimeEnter();
        if (false) {
            PreferencesManager.getInstance().saveIsFirstTimeEnter(false);
            showSplashViewPager();
        } else {
            if (NetWorkTypeUtils.isNetAvailable() && !Utils.isMonkeyRunning()) {
                new RequestPublicIpTask(MoviesApplication.getInstance()).start();
                new RequestInitInfoTask(MoviesApplication.getInstance(), new InitDataRequestResultListener()).start();
                launchDuration.setRequestInitPort(System.currentTimeMillis()+"");
            } else {
                LogUtils.e(TAG, "net is err");
                showDefaultLaunchAndRedirect();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.direct_to_main_ll:
            case R.id.ad_text:
                isDirectToMainclick = true;
                redirectToMain();
                break;
            case R.id.ad_image:
                isAdClick = true;
                if (!TextUtils.isEmpty(adUrl)) {
                    redirectToMain();
                    // 大数据点击上报
                    BigDataApi.bigDataAdReport(BigDataConstants.ACODE_CLICK, BigDataConstants.AD_START_CLICK, this);
                    UmengEventPoster.doPost(UmengEventPoster.SERVERAD_CLICK, "position", "splash");
                }
                break;
            case R.id.tv_direct_main:
                redirectToMain();
                break;
        }
    }

    /**
     * @param adType
     * @param isPlatControl
     * @param isCityControl
     */
    private void isShowAd(int adType, boolean isPlatControl,
                          boolean isCityControl) {
        switch (adType) {
            case 1:
                isShowAd = false;
                break;
            case 2:
                isShowAd = true & isPlatControl & isCityControl;
                break;
            case 3:
                isShowAd = true & isPlatControl & isCityControl;
                break;
            default:
                isShowAd = false;
                break;
        }
    }

    private void showLaunchImage(String url) {
        mLaunchImage.setVisibility(View.VISIBLE);
        LogUtils.e(TAG, "show request image");
        ImageLoader.getInstance().displayImage(url, mLaunchImage);
    }

    private void showAdImage() {
        final long startTime = System.currentTimeMillis();
        LogUtils.e(TAG, "5-->on showAdImage and adImageUrl is " + adImageUrl);
        ImageLoader.getInstance().displayImage(adImageUrl, mAdImage, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {
                LogUtils.e(TAG, "start time is " + startTime);
                LogUtils.e(TAG, "6-->on showAdImage and onLoadingStarted called");
            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {
                LogUtils.e(TAG, "on showAdImage and onLoadingFailed called");
                redirectToMain();
            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                LogUtils.e(TAG, "load ad use time is " + (System.currentTimeMillis() - startTime));
                LogUtils.e(TAG, "7-->on showAdImage and onLoadingComplete called");
                mLaunchImage.setVisibility(View.GONE);
                mAdLayout.setVisibility(View.VISIBLE);
                directToMianLl.setVisibility(View.VISIBLE);
                start();
                // 大数据曝光上报
                BigDataApi.bigDataAdReport(BigDataConstants.ACODE_EXPOSURE, BigDataConstants.AD_START_SHOW, SplashActivity.this);
                UmengEventPoster.doPost(UmengEventPoster.SERVERAD_SHOW, "position", "splash");
            }

            @Override
            public void onLoadingCancelled(String s, View view) {
                LogUtils.e(TAG, "on showAdImage and onLoadingCancelled called");
                redirectToMain();
            }
        });
    }

    // 开始计时
    public void start() {
        leftTime = adTime;
        isRun = true;
        runTask();
    }

    // 倒计时
    public void runTask() {
        if (isRun) {
            mAdTextTime.setText(String.valueOf(leftTime) + " ");
            if (leftTime == 0) {
                isRun = false;
                if(SplashActivity.class.getName().equals(MoviesApplication.getInstance().getRunningActivityName())){
                    redirectToMain();
                }
                return;
            }
            leftTime--;
            mHandler.postDelayed(mTask = new Runnable() {
                @Override
                public void run() {
                    runTask();
                }
            }, 1000);
        } else {
            redirectToMain();
        }
    }

    private void redirectToMain() {
        if(getIntent() !=  null && "back".equals(getIntent().getStringExtra("from"))){

        }else{
            mHandler.removeMessages(MSG_START_MAIN);
            if (mTask != null) mHandler.removeCallbacks(mTask);
            Intent intent = null;
            if (getIntent().getBooleanExtra(START_FROM_NOTIFICATION, false)) {
                intent = new Intent(getIntent());
                intent.setClass(this, NewMainActivity.class);
            } else {
                intent = new Intent(this, NewMainActivity.class);
            }
            Bundle bundle = new Bundle();
            bundle.putString(ADURL, adUrl);
            bundle.putSerializable(Utils.AD_INFO, mServerAdInfo);
            bundle.putBoolean(ISADCLICK, isAdClick);
            bundle.putSerializable(LAUNCHLOG,launchDuration);
            intent.putExtras(bundle);
            startActivity(intent);
            overridePendingTransition(0, 0);
        }
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                exitBy2Click();
                return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exitBy2Click() {
        Timer tExit = null;
        if (backCount < 1) {
            backCount = 1; // 准备退出
            UIs.showToast(R.string.exit_tip);
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    backCount = 0; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            if (mTask != null)
                mHandler.removeCallbacks(mTask);
            finish();
        }
    }

    private class InitDataRequestResultListener implements RequestResultListener<InitInfo> {
        @Override
        public boolean onRequestFailed() {
            LogUtils.e(TAG, "请求失败");
            new RequestAdTask(MoviesApplication.getInstance(), MoviesHttpApi.LAUNCH, new LzunchAdRequestResultListener()).start();
            launchDuration.setRequestAdConfig(System.currentTimeMillis()+""); // 请求广告配置接口埋点
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, final InitInfo result) {
            mHandler.removeMessages(MSG_START_MAIN);
            if (result != null) {
                if (!TextUtils.isEmpty(result.getSplash())) {
                    String url = result.getSplash();
                    LogUtils.e(TAG, "3-->request launch_image url is " + url);
                    launchDuration.setShowDePic(System.currentTimeMillis()+"");// 展示default图埋点
                    showLaunchImage(url);
                }

                PreferencesManager.getInstance().saveIsReport(result.isReport()? "1":"0");
                //            save download rate
                int downloadRate = result.getDownloadRate();
                PreferencesManager.getInstance().setSpeed(downloadRate);
                PreferencesManager.getInstance().setSplashInterval(result.getSplashInterval());
                PreferencesManager.getInstance().setSplashLimit(result.getSplashLimit());
                SharePreferenceManager.saveVaule(MoviesApplication.getInstance(), SharePreferenceManager.YIDIAN_TAG, result.getYiDianTag());
                if(BuildConfig.DEBUG){
                    Toast.makeText(MoviesApplication.getInstance(), result.getSplashLimit() + "----" + BigDataConstants.AUID.hashCode()%10, Toast.LENGTH_LONG).show();
                }
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        new RequestAdTask(MoviesApplication.getInstance(), MoviesHttpApi.LAUNCH, new LzunchAdRequestResultListener()).start();
                        launchDuration.setRequestAdConfig(System.currentTimeMillis()+"");// 请求广告配置接口埋点
                    }
                });
                String tags = result.getTags();
                PreferencesManager.getInstance().saveTags(tags);
                setJPushTags(tags);
            } else {
                LogUtils.e(TAG, "parser fail");
                new RequestAdTask(MoviesApplication.getInstance(), MoviesHttpApi.LAUNCH, new LzunchAdRequestResultListener()).start();
                launchDuration.setRequestAdConfig(System.currentTimeMillis()+"");// 请求广告配置接口埋点
            }
        }

        @Override
        public void onPreRequest() {

        }
    }

    private void setJPushTags(String tags) {
        try {
            boolean hasOnePointTag = false;
            if (!TextUtils.isEmpty(tags)) {
                String[] tagsArr = tags.split(",");
                if (tagsArr == null || tagsArr.length == 0) {
                    tagsArr = new String[1];
                    tagsArr[0] = tags;
                }
                for (int i = 0; i < tagsArr.length; i++) {
                    if (tagsArr[i] != null && tagsArr[i].startsWith(MoviesConstant.TAGS_YIDIAN)) {
                        hasOnePointTag = true;
                        Set<String> tagsSet = new HashSet<>();
                        tagsSet.add(tagsArr[i]);
                        tagsSet.add(MoviesUtils.getClientVersionName());
                        JPushInterface.setTags(this, 0, tagsSet);
                        break;
                    }
                }
            }
            if (!hasOnePointTag) {
                JPushInterface.cleanTags(this, 0);
            }
        } catch (Exception e) {
            com.apkfuns.logutils.LogUtils.e("Set jPush tags error:" + e.getMessage());
        }
    }

    private void showLaunchAd(NewAdDataBean result) {
        // 启动广告图
        ServerPayload payload = null;
        int adType = 0;
        if(result.payload instanceof ServerPayload){
            payload = (ServerPayload) result.payload;
            adType = 2;
        }
        if(payload == null){
            redirectToMain();
            return;
        }
        if (!TextUtils.isEmpty(payload.pic)) {
            adImageUrl = payload.pic;
        }
        isShowAd(adType, isPlatControll, isCityControll); // 广告显示与否
        if (TextUtils.isEmpty(adImageUrl))
            isShowAd = false;
        if (!TextUtils.isEmpty(payload.lp)) {
            adUrl = payload.lp;
            mServerAdInfo = payload;
        }

        LogUtils.e(TAG, "isShowAd is " + isShowAd);
        if (isShowAd) {
            showAdImage();
        } else {
            redirectToMain();
        }
    }

    private class LzunchAdRequestResultListener implements
            RequestResultListener<NewAdDataBean> {

        @Override
        public boolean onRequestFailed() {
            showDefaultLaunchAndRedirect();
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, NewAdDataBean result) {
            if (result != null) {
                AdRequestStatis.selfResponseReport(result, SelfDataConstant.AD_PO_SPLASH);
                if (Utils.GDT_AD.equalsIgnoreCase(result.provider)) {
                    if(PreferencesManager.getInstance().getSplashGdtShowtimes() < PreferencesManager.getInstance().getSplashLimit()){
                        showGdtNativeAd(((SDKPayload)result.payload).adId);
                        launchDuration.setRequestAdData(System.currentTimeMillis()+"");// 请求相应的广告数据埋点
                    }else{
                        redirectToMain();
                    }
                } else if(Utils.BAIDU_AD.equalsIgnoreCase(result.provider)){
                    AdStatisticsSp.savaOneUp(SplashActivity.this, AdStatisticsSp.BAIDUSPLASHADRESPONSE);
                    showBaiduSplashAd(((SDKPayload)result.payload).adId);
                    launchDuration.setRequestAdData(System.currentTimeMillis()+"");// 请求相应的广告数据埋点
                } else if(Utils.GDT_SPLASH_AD.equalsIgnoreCase(result.provider)){
                    showGdtSplashAd(((SDKPayload)result.payload).adId);
                    launchDuration.setRequestAdData(System.currentTimeMillis()+"");// 请求相应的广告数据埋点
                }else if (Utils.HZ_AD.equals(result.provider)) {
                    HzPayAdView hzAdView = new HzPayAdView(SplashActivity.this, adView, "splash");
                    hzAdView.setHzAd(((HzPayload)result.payload).ad);
                    start();
                    directToMianLl.setVisibility(View.VISIBLE);
                    launchDuration.setRequestAdDataSucc(System.currentTimeMillis()+"");// 请求广告数据成功埋点
                } else if (Utils.YZ_AD.equals(result.provider)) {
                    YzPayAdView yzAdView = new YzPayAdView(SplashActivity.this, adView, "splash");
                    yzAdView.setYzAd(((YzPayload)result.payload).ad);
                    start();
                    directToMianLl.setVisibility(View.VISIBLE);
                    launchDuration.setRequestAdDataSucc(System.currentTimeMillis()+"");// 请求广告数据成功埋点
                } else if (Utils.XF_AD.equals(result.provider)) {
                    XfPayAdView xfAdView = new XfPayAdView(SplashActivity.this, adView, "splash");
                    xfAdView.setXfAd(((XfPayload)result.payload).ad);
                    start();
                    directToMianLl.setVisibility(View.VISIBLE);
                    launchDuration.setRequestAdDataSucc(System.currentTimeMillis()+"");// 请求广告数据成功埋点
                } else if (Utils.TT_AD.equals(result.provider)) {
                    TtPayAdView ttPayAdView = new TtPayAdView(SplashActivity.this, adView, "splash");
                    ttPayAdView.setTtAd(((TtPayload)result.payload).ad);
                    start();
                    directToMianLl.setVisibility(View.VISIBLE);
                    launchDuration.setRequestAdDataSucc(System.currentTimeMillis()+"");
                }else {
                    showLaunchAd(result);
                    launchDuration.setRequestAdDataSucc(System.currentTimeMillis()+"");// 请求广告数据成功埋点
                }
            }else{
                showDefaultLaunchAndRedirect();
            }
        }

        @Override
        public void onPreRequest() {

        }
    }

    /**
     * 设置广点通的闪屏广告
     * @param gdtId
     */
    private void showGdtNativeAd(String gdtId) {
        GdtNativeAdView gdtSplashAd = new GdtNativeAdView(SplashActivity.this, "splash", "splash");
        gdtSplashAd.setAdListener(new MyOnAdListener() {
            @Override
            public void onAdDismissed() {

            }

            @Override
            public void onAdFailed() {
                redirectToMain();
            }

            @Override
            public void onAdPresent() {

            }

            @Override
            public void onAdSuccess(Object obj) {
                start();
                directToMianLl.setVisibility(View.VISIBLE);
                launchDuration.setRequestAdDataSucc(System.currentTimeMillis()+"");
            }
        });
        gdtSplashAd.loadAD(gdtId);
    }

    /**
     * 设置广点通的闪屏广告
     * @param gdtId
     */
    private void showGdtSplashAd(String gdtId) {
        GdtSplashAdView gdtSplashAd = new GdtSplashAdView(SplashActivity.this, directToMianLl, "launch");
        gdtSplashAd.setAdListener(new MyOnAdListener() {
            @Override
            public void onAdDismissed() {

            }

            @Override
            public void onAdFailed() {
                redirectToMain();
            }

            @Override
            public void onAdPresent() {

            }

            @Override
            public void onAdSuccess(Object obj) {
                start();
                directToMianLl.setVisibility(View.VISIBLE);
                launchDuration.setRequestAdDataSucc(System.currentTimeMillis()+"");
            }
        });
        gdtSplashAd.loadAD(gdtId);
    }

    private void showBaiduSplashAd(String adPlaceId) {
        adView.setVisibility(View.VISIBLE);
        mBaiduAdLayout.setVisibility(View.VISIBLE);
        BaiduNativeAdView baiduSplashAd = new BaiduNativeAdView(SplashActivity.this, mBaiduAdLayout, "splash");
        baiduSplashAd.setAdListener(new MyOnAdListener() {
            @Override
            public void onAdDismissed() {

            }

            @Override
            public void onAdFailed() {
                redirectToMain();
            }

            @Override
            public void onAdPresent() {

            }

            @Override
            public void onAdSuccess(Object obj) {
                start();
                directToMianLl.setVisibility(View.VISIBLE);
                launchDuration.setRequestAdDataSucc(System.currentTimeMillis()+"");
            }
        });
        baiduSplashAd.setBaiduAd(adPlaceId);

    }

    private void jump() {
        // 如果当前应用在前台则跳转，解决当显示开屏广告时，用户点击home键进入后台，此时仍会跳转的问题
        boolean background = Utils.isBackground(getApplicationContext());
        if (isJump && !background) {
            // 如果跳转成功过则不再跳转
            isJump = false;
            startActivity(new Intent(SplashActivity.this,
                    NewMainActivity.class));
            overridePendingTransition(0, 0);
            finish();
        }
    }

    private static class RequestInitInfoTask extends MoviesHttpAsyncTask<InitInfo> {

        private RequestResultListener<InitInfo> mListener;
        @Override
        public void netNull() {
            super.netNull();
            if (mListener != null){
                mListener.onRequestFailed();
            }
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            if (mListener != null){
                mListener.onRequestFailed();
            }
        }

        public RequestInitInfoTask(Context context, RequestResultListener<InitInfo> mListener) {
            super(context);
            this.mListener = mListener;
        }

        @Override
        public LVideoDataHull<InitInfo> doInBackground() {
            return MoviesHttpApi.requestInit(new InitInfoParser());
        }

        @Override
        public void onPostExecute(int updateId, InitInfo result) {
            if (mListener != null) {
                mListener.onRequestSuccess(updateId, result);
            }
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
            if (mListener != null){
                mListener.onRequestFailed();
            }
        }

    }

    private void showDefaultLaunchAndRedirect() {
        mHandler.removeMessages(MSG_START_MAIN);
        isShowAd = false;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                redirectToMain();
            }
        }, TIMEINTERVAL);
    }

    @Override
    protected void onPause() {
        LogCat.e(TAG, "onPause");
        super.onPause();
    }

    @Override
    protected void onResume() {
        LogUtils.e(TAG, "onResume");
        super.onResume();
        if(mResumeTimes == 0){
            mResumeTimes = 1;
        }else{
            redirectToMain();
        }
    }
	
	 @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case MSG_START_MAIN:
                redirectToMain();
                break;
        }
        return false;
    }
}
